<?php

declare(strict_types=1);
/**
 * 模版语法参数传递
 * Author: Zane
 * Email: 873934580@qq.com
 * Date: 2022/6/7.
 */

namespace Zane\View\Service;

use Illuminate\Support\Str;

/**
 * @property string limit
 * @property array order
 * @property string lang
 */
class Transfer
{
    private $param;

    private function __construct($param)
    {
        $this->param = $param;
    }

    public function __call($name, $arguments)
    {
        $name = lcfirst(Str::afterLast($name, 'get'));
        if (!isset($this->param[$name])) {
            return $arguments[0] ?? null;
        }

        return $this->get($name);
    }

    public function __get($name)
    {
        return $this->get($name);
    }

    public function __toString(): string
    {
        return md5(serialize($this->param));
    }

    /**
     * 获取限制条数.
     *
     * @param int $default
     *
     * @return int|mixed
     */
    public function getLimit(int $default = 10)
    {
        if (blank($default)) {
            $default = 10;
        }

        return $this->param['limit'] ?? $default;
    }

    public function getOrder($default = ['id' => 'desc']): array
    {
        $result = [];
        $order = $this->param['order'] ?? $default;
        if (!\is_array($order)) {
            $order = explode(',', $order);
        }

        foreach ((array) $order as $key => $val) {
            if (is_numeric($key)) {
                $val = explode('|', $val);
                $result[trim($val[0])] = trim($val[1] ?? 'desc');
            } else {
                $result[trim($key)] = trim($val);
            }
        }

        return $result;
    }

    public function getLang()
    {
        return $this->param['lang'] ?? config('app.locale', 'zh-cn');
    }

    public function get($key, $default = null)
    {
        if (!isset($this->param[$key])) {
            return $default;
        }
        if (\is_array($this->param[$key])) {
            return $this->param[$key];
        }
        if (\is_string($this->param[$key])) {
            $params = explode('|', $this->param[$key]);
            if (\count($params) > 1) {
                return $params;
            }
        }

        return $this->param[$key];
    }

    public static function build($param = []): self
    {
        return new self($param);
    }
}
